package cn.iocoder.yudao.module.contract.controller.admin.order;

import cn.hutool.json.JSONArray;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.contract.dal.dataobject.contractTemplate.ContractTemplateDO;
import cn.iocoder.yudao.module.contract.dal.dataobject.orderContract.OrderContractDO;
import cn.iocoder.yudao.module.contract.service.contractTemplate.ContractTemplateService;
import cn.iocoder.yudao.module.contract.service.orderContract.OrderContractService;
import cn.iocoder.yudao.module.contract.webservice.ContractWebService;
import cn.iocoder.yudao.module.contract.webservice.ZSD_JS_010;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;

import cn.iocoder.yudao.module.contract.controller.admin.order.vo.*;
import cn.iocoder.yudao.module.contract.dal.dataobject.order.OrderDO;
import cn.iocoder.yudao.module.contract.dal.dataobject.order.OrderDetailsDO;
import cn.iocoder.yudao.module.contract.service.order.OrderService;

@Tag(name = "管理后台 - 订单")
@RestController
@RequestMapping("/contract/order")
@Validated
@Slf4j
public class OrderController {

    @Resource
    private OrderService orderService;
    @Resource
    private OrderContractService orderContractService;
    @Resource
    private ContractTemplateService templateService;
    @Resource
    private ContractWebService contractWebService;

    @PostMapping("/create")
    @Operation(summary = "创建订单")
    @PreAuthorize("@ss.hasPermission('contract:order:create')")
    public CommonResult<Long> createOrder(@Valid @RequestBody OrderSaveReqVO createReqVO) {
        return success(orderService.createOrder(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新订单")
    @PreAuthorize("@ss.hasPermission('contract:order:update')")
    public CommonResult<Boolean> updateOrder(@Valid @RequestBody OrderSaveReqVO updateReqVO) {
        orderService.updateOrder(updateReqVO);
        return success(true);
    }

    @PutMapping("/editContract")
    @Operation(summary = "修改订单并生成合同")
//    @PreAuthorize("@ss.hasPermission('contract:order:update')")
    public CommonResult<?> editContract(@Valid @RequestBody OrderSaveReqVO updateReqVO) {
        // 更新
        OrderDO updateObj = BeanUtils.toBean(updateReqVO, OrderDO.class);
        ContractTemplateDO contractTemplate = templateService.getOne(Wrappers.<ContractTemplateDO>lambdaQuery().eq(ContractTemplateDO::getContractTypeCode, updateReqVO.getHtdymb()).eq(ContractTemplateDO::getClientCode, updateReqVO.getKunnr()), false);
        if (contractTemplate == null) {
            contractTemplate = templateService.getOne(Wrappers.<ContractTemplateDO>lambdaQuery().eq(ContractTemplateDO::getContractTypeCode, updateReqVO.getHtdymb()).isNull(ContractTemplateDO::getClientId), false);
            if (contractTemplate == null) {
                throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), "合同模板不存在");
            }
        }
//        ContractTemplateDO contractTemplate = templateService.getOne(Wrappers.<ContractTemplateDO>lambdaQuery().eq(ContractTemplateDO::getContractTypeCode,updateReqVO.getHtdymb()),false);
//        if(contractTemplate ==null){
//            throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),"合同模板不存在");
//        }
        OrderContractDO orderContrac = orderContractService.getOne(new LambdaQueryWrapper<OrderContractDO>().eq(OrderContractDO::getOrderId, updateReqVO.getId()));
        if (orderContrac == null) {
            return error("合同不存在");
        }
        orderService.updateById(updateObj);
        orderContractService.generateContractFile(orderContrac);
        orderContractService.updateById(orderContrac);
        String result = "操作成功";
        if ("0".equals(orderContrac.getStatus())) {
            result = "修改成功,合同生成失败-" + orderContrac.getAbnormalCause();
            return success(result);
        }

        return success(result);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除订单")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('contract:order:delete')")
    public CommonResult<Boolean> deleteOrder(@RequestParam("id") Long id) {
        orderService.deleteOrder(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得订单")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('contract:order:query')")
    public CommonResult<OrderRespVO> getOrder(@RequestParam("id") Long id) {
        OrderDO order = orderService.getOrder(id);
        return success(BeanUtils.toBean(order, OrderRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得订单分页")
    @PreAuthorize("@ss.hasPermission('contract:order:query')")
    public CommonResult<PageResult<OrderRespVO>> getOrderPage(@Valid OrderPageReqVO pageReqVO) {
        PageResult<OrderDO> pageResult = orderService.getOrderPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, OrderRespVO.class));
    }

    @GetMapping("/detailsPage")
    @Operation(summary = "获得订单分页")
    public CommonResult<IPage<OrderDetailsRespVO>> getOrderDetailsPage(@Valid OrderDetailsPageReqVO pageReqVO) {
        IPage<OrderDetailsRespVO> pageResult = orderService.getOrderDetailsPage(pageReqVO);
        return success(pageResult);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出订单 Excel")
    @PreAuthorize("@ss.hasPermission('contract:order:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportOrderExcel(@Valid OrderDetailsPageReqVO pageReqVO,
                                 HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<OrderDetailsRespVO> list = orderService.getOrderDetailsPage(pageReqVO).getRecords();
        // 导出 Excel
        ExcelUtils.write(response, "订单.xls", "数据", OrderDetailsExportVO.class,
                BeanUtils.toBean(list, OrderDetailsExportVO.class));
    }

    // ==================== 子表（订单明细） ====================

    @GetMapping("/order-details/list-by-order-id")
    @Operation(summary = "获得订单明细列表")
    @Parameter(name = "orderId", description = "订单id")
    @PreAuthorize("@ss.hasPermission('contract:order:query')")
    public CommonResult<List<OrderDetailsDO>> getOrderDetailsListByOrderId(@RequestParam("orderId") Long orderId) {
        return success(orderService.getOrderDetailsListByOrderId(orderId));
    }


    @PostMapping("/orderSync")
    @Operation(summary = "订单同步")
    public CommonResult<?> orderSync(@RequestBody OrderSyncReqVO syncReqVO) {
//        String startDate = "";
//        String endDate = "";
//        if("1".equals(syncReqVO.getSyncType())){
//            startDate = syncReqVO.getStartDate()[0];
//            endDate = syncReqVO.getStartDate()[1];
//        }
        if (StringUtils.isBlank(syncReqVO.getVbeln())) {
            syncReqVO.setVbeln("");
        }
        String result = contractWebService.getOrderList(syncReqVO.getVbeln());
        if (result.contains("同步失败-")) {
            return error(result);
        }
        return success(result);
    }
}